var express = require("express");

var bodyParser = require("body-parser");

var cookieParser = require("cookie-parser");

var fs = require("fs");

//导入multer模块，multer模块用于处理表单类型数据(Content-Type
//为multipart/form-data)，也可以用于文件上传。
var multer = require("multer");

//使用multer生成一个请求处理函数，其中可以设置上传文件的
//存储位置。
var storage = multer.diskStorage({
	destination:function(req,file,cb){
		cb(null,"www/headers/");
	},
	filename:function(req,file,cb){
		cb(null,req.cookies.account+".jpg");
	}
});

var upload = multer({storage});


var app = express();

app.use(express.static("www"));

app.use(bodyParser.urlencoded({extended:false}));

app.use(cookieParser());

//注册接口
app.post("/regist-api",function(req,res){
	var str = JSON.stringify(req.body);
	var fileName = "users/"+req.body.account+".json";
	
	if(fs.existsSync(fileName)){
		res.json({err:1,msg:"用户名已存在"});
	}else{
		fs.writeFile(fileName,
		str,function(err){
			if(!err){
				res.json({err:0,msg:"注册成功"});
			}else{
				res.json({err:2,msg:"服务器存储失败"});
			}
		});
	}
	fs.exists('users', function(ex){
        if( !ex ){
            fs.mkdirSync('user')
            saveFile()
        } else {
            saveFile()
        }
    })
});


//登录接口
app.post("/login-api",function(req,res){
	console.log(req.body);
	//生成touken的函数
	function makeToken(){
		var sourceStr = "123457890asdfghjklzxcvbnm";
		var token = "";
		for (var i = 0;i<10;i++) {
			token += sourceStr[Math.floor(Math.random()*sourceStr.length)];
		}
		return token;
	}
	
	var fileName = "users/"+req.body.account+".json";
	
	if(!fs.existsSync(fileName)){
		res.json({err:1,msg:"用户不存在"});
	}else{
		fs.readFile(fileName,function(err,data){
			if(err){
				res.json({err:2,msg:"服务器内部错误"});
			}else{
				var user = JSON.parse(data);
				if(req.body.psw == user.psw){
					//登录成功，先生成token
					var token = makeToken();
					//通过cookie把token发给客户端。
					res.cookie("token",token);
					res.cookie("account",user.account);
					//服务端也要存储token
					user.token = token;
					var str = JSON.stringify(user);
					fs.writeFile(fileName,str,function(err){
						res.json({err:0,msg:"登录成功"});
					});
				}else{
					res.json({err:3,msg:"密码错误"});
				}
			}
		});
	}
});


//上传头像接口
app.post("/upload-api",upload.single("header"),function(req,res){
	res.send(
	"上传成功"+
	"<script>"+
	"setTimeout(function(){"+
	'location.href = "/";'+
	"},3000);"+
	"</script>"
	);
	
});


//验证请求是否已经登录的函数
function isLogin(req){
	
	var fileName = "users/"+req.cookies.account+".json";
	
	if(!fs.existsSync(fileName)){
		return false;
	}
	
	var data = fs.readFileSync(fileName);
	
	var user = JSON.parse(data);
	if(user.token&& (user.token== req.cookies.token)){
		return true;
	}else{
		return false;
	}
	
}

//用于存放所有问题的数组。
var allQuestion;

if(fs.existsSync("allQuestion/file.json")){
	var data = fs.readFileSync("allQuestion/file.json");
	allQuestion = JSON.parse(data);
}else{
	allQuestion = [];
}

//存放当前的最大ID
var questionID;
if(fs.existsSync("allQuestion/id.json")){
	var data = fs.readFileSync("allQuestion/id.json").toString();
	questionID = Number(data);
}else{
	questionID= 0;
}


//提交问题接口
app.post("/ask-api",function(req,res){
	if(!isLogin(req)){
		res.json({err:1,msg:"没有登录"});
	}else{
		//验证数据
		//.............
		var text = req.body.question;
		text = text.replace(/</g,"&lt;");
		text = text.replace(/>/g,"&gt;");
		
		
		console.log(text);
		
        questionID++;
        
        fs.writeFileSync("allQuestion/id.json",questionID);
        
		var question = {
			id:questionID,
			account:req.cookies.account,
			ip:req.ip.substr(7),
			date:new Date(),
			question:text,
			answers:[]
		}
		
		allQuestion.unshift(question);
		
		var str = JSON.stringify(allQuestion);
		
		fs.writeFile("allQuestion/file.json",str,function(err){
			if(!err){
				res.json({err:0,msg:"提问成功"});
			}else{
				console.log(err);
				res.json({err:2,msg:"服务器存储失败"});
			}
		});
		
	}
});


//问题列表接口
app.get("/allQuestion-api",function(req,res){
	
	res.json({err:0,data:allQuestion});
});


//回答问题接口
app.post("/answer-api",function(req,res){
	if(!isLogin(req)){
		res.json({err:1,msg:"没有登录"});
	}else{
		var question = allQuestion.find(function(obj){
			return obj.id == req.body.id;
		});
		
		var answer = {
			account:req.cookies.account,
			ip:req.ip.substr(7),
			date:new Date(),
			content:req.body.content
		}
		
		question.answers.push(answer);
		
		var str = JSON.stringify(allQuestion);
		fs.writeFile("allQuestion/file.json",str,function(err){
			if(!err){
				res.json({err:0,msg:"回答成功"});
			}else{
				console.log(err);
				res.json({err:2,msg:"服务器存储失败"});
			}
		});
		
	}
});

Array.prototype.removeObject = function(obj){
	var index = this.indexOf(obj);
	if(index>=0){
		this.splice(index,1);
	}
}

//删除问题接口
app.post("/delete-api",function(req,res){
	if(!isLogin(req)){
		res.json({err:1,msg:"没有登录"});
	}else{
		var question = allQuestion.find(function(obj){
			return obj.id == req.body.id;
		});
		if(question.account == req.cookies.account){
		allQuestion.removeObject(question);
		var str = JSON.stringify(allQuestion);
		fs.writeFile("allQuestion/file.json",str,function(err){
			if(!err){
				res.json({err:0,msg:"删除成功"});
			}else{
				console.log(err);
				res.json({err:2,msg:"服务器存储失败"});
			}
		});
		}else{
			res.json({err:0,msg:"没有操作权限"});
		}
	}
});


app.listen(800,function(){
	console.log("服务器已开启");
});
